package main.Communication;

import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.SocketException;

import main.Communication.Interface.chatInterface;

/**
 * 通讯子进程，用于接收主机信息
 * @author svitter
 */
class chatClient implements Runnable, chatInterface { 
	private Socket 				socket;
	private ObjectInputStream 	dis   = null;
	private ObjectOutputStream 	dos  = null;
	private boolean 			bConnected      = false;
	private int					uid;

	/**
	 * 开启分线程
	 * @param socket
	 * @param uid
	 */
	public chatClient(Socket socket, int uid) {
		this.uid = uid;
		this.socket = socket;
		try {
			dis = new ObjectInputStream(socket.getInputStream());
			dos = new ObjectOutputStream(socket.getOutputStream());
			bConnected = true;

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void send(Object mes) {
		try {
			dos.writeObject(mes);
		} catch (SocketException e) {
            System.out.println("[Server]: A Client" + "退出了...");
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void handle(Object umd) {
        System.out.println("[Server]: handle information.");
	}
	
	/**
     * 接受客户端发来的信息
     */
	public void run() {
		try {
			while (bConnected) {
				Object umd = dis.readObject();

				// handle information
				handle(umd);
			}
		} catch (EOFException e) {
            // a Client 之后添加一个特殊id
            System.out.println("[Server]: " + uid + " Client" + "退出了");
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (dis != null)
				if (socket != null)
					try {
						dis.close();
						socket.close();
						dos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
		}
	}

	public ObjectInputStream getDis() {
		return this.dis;
	}
	
	public ObjectOutputStream getDos() {
		return this.dos;
	}
	
	public Socket getSocket() {
		return this.socket;
	}
	
	/**
	 * 获取用户编号
	 * @return
	 */
	public int getUID() {
		return this.uid;
	}
}
